﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Drawing;
using System.Xml;
using GoogleChartSharp;
using SecurityUser = AdventureWorks.DashboardGroep7.securityService.MembershipUser;


namespace AdventureWorks.DashboardGroep7
{
    public partial class Default1 : System.Web.UI.Page
    {
        private List<Component> componentList = new List<Component>();
        private List<String> values = new List<String>();
        private int groepService;
        //connect to reportservice
        private groep6Service.AverageProductLifecycle groep6Service = new groep6Service.AverageProductLifecycle();
        private groep7Service.MonthOverviewShippingMethodGroep7 groep7Service = new groep7Service.MonthOverviewShippingMethodGroep7();  
      //private groep8Service.ReportService reportService = new groep8Service.ReportService();
        

        
        //connect to security service
        private securityService.Service1 securityService = new securityService.Service1();

        protected void Page_Load(object sender, EventArgs e)
        { 
            // get reportId from menu
            String passedArgument = Request.Params.Get("__EVENTARGUMENT");
            //Response.Write(passedArgument);
            try
            {

                passedArgument = passedArgument.Replace("b", "");
            }
            catch { }
            //Response.Write(Session["groepService"]);

            if (passedArgument == "" && Session["groepService"].ToString() != "")
            {
                this.groepService = (Int32)Session["groepService"];
            }
            else
            {
                //determine what report has te be loaded
                switch (passedArgument)
                {
                    default:
                        this.groepService = 6;

                        break;
                    case "6":
                        this.groepService = 6;
                        break;
                    case "7":
                        this.groepService = 7;
                        break;
                    case "8":
                        break;
                }
            }


            Session["groepService"] = this.groepService;
            //check whether user is logged in, if so make controls visible
            if (Session["username"] == null)
            {
                div_reportControls.Visible = false;
                div_reportResult.Visible = false;
            }
            else
            {
                div_loginControls.Visible = false;
                div_reportControls.Visible = true;
                div_reportResult.Visible = true;
            }
            
            generateReportInput();
        }

        private void generateReportInput()
        {
            //get required components for report
            DataSet dataSet = new DataSet();
            switch (this.groepService)
            {
                case 6:
                    dataSet = this.groep6Service.getComponents();
                    break;
                case 7:
                    dataSet = this.groep7Service.getComponents();
                    break;
            }
           


            //read data from dataset
            DataTable dataTableComponents = dataSet.Tables[0];
            DataTable dataTableItems = dataSet.Tables[1];
            DataRowCollection componentRowCollection = dataTableComponents.Rows;
            DataRowCollection itemRowCollection = dataTableItems.Rows;

            //create components
            foreach (DataRow row in componentRowCollection)
            {
                Component component = new Component();
                component.Id = Int32.Parse(row[dataTableComponents.Columns["component_Id"]].ToString());
                component.Label = row[dataTableComponents.Columns["label"]].ToString();
                component.Type = row[dataTableComponents.Columns["type"]].ToString();

                List<String> items = new List<string>();
                foreach (DataRow item in itemRowCollection)
                {
                    items.Add(item[dataTableItems.Columns[1]].ToString());
                }
                component.Items = items;

                this.componentList.Add(component);
            }

                // create GUI with components
                foreach (Component component in this.componentList)
                {
                    Panel panel = new Panel();
                    panel.BackColor = Color.White;
                    panel.Width = 200;
                    panel.Style["float"] = "left";
                    panel.Style["margin-right"] = "25px";

                    String type = component.Type;
                    switch (type)
                    {
                        case "label":
                            break;
                        case "string":
                            Label label = new Label();
                            label.Text = component.Label;
                            TextBox textbox = new TextBox();
                            textbox.ID = component.Id.ToString();

                            panel.Controls.Add(label);
                            panel.Controls.Add(textbox);
                            break;
                        case "list":
                            Label listLabel = new Label();
                            listLabel.Text = component.Label;
                            DropDownList dropDownList = new DropDownList();
                            dropDownList.ID = component.Id.ToString();

                            foreach (String item in component.Items)
                            {
                                ListItem li = new ListItem(item, item);
                                dropDownList.Items.Add(li);
                            }
                            dropDownList.EnableViewState = false;
                            panel.Controls.Add(listLabel);
                            panel.Controls.Add(dropDownList);

                           // dropDownList.Style["float"] = "right";
                            break;
                        case "datetime":

                            Label lbl = new Label();
                            lbl.Text = component.Label;

                            Calendar cal = new Calendar();
                            cal.SelectedDate = DateTime.Now;
                            cal.ID = component.Id.ToString();

                            panel.Controls.Add(lbl);
                            panel.Controls.Add(cal);
                            break;
                    }

                    div_content.Controls.Add(panel);
                
            }
        }

        protected void btn_submit_Click(object sender, EventArgs e)
        {
            // read components
            foreach (Component component in this.componentList)
            {
                String id = component.Id.ToString();
                ContentPlaceHolder main = (ContentPlaceHolder)Master.FindControl("main");
                //find control in GUI
                Control control = main.FindControl(id);
                if (control != null)
                {
                    switch (control.GetType().ToString())
                    {
                        default:
                            Response.Write(control.ToString());
                            break;

                        //dropdown
                        case "System.Web.UI.WebControls.DropDownList":
                            DropDownList dropDownList = (DropDownList)main.FindControl(id);
                            this.values.Add(dropDownList.SelectedValue);
                            break;

                        //textbox
                        case "System.Web.UI.WebControls.TextBox":
                            TextBox textBox = (TextBox)main.FindControl(id);
                            this.values.Add(textBox.Text);
                            break;

                        //calendar 
                        case "System.Web.UI.WebControls.Calendar":
                            Calendar calendar = (Calendar)main.FindControl(id);
                            this.values.Add(calendar.SelectedDate.ToString());
                            break;
                    }
                }
            }

            sendVariables();
        }

        ///
        /// <summary>Sends the variables from compontents back to the reportservice</summary>
        ///
        private void sendVariables()
        {
            DataSet dataSet = new DataSet();
            XmlDocument xmlDoc = new XmlDocument();

            //Build XML
            XmlElement components = xmlDoc.CreateElement("root");
            xmlDoc.AppendChild(components);

            // add report level
            XmlElement levelsElement = xmlDoc.CreateElement("level");
            components.AppendChild(levelsElement);
            XmlElement levelElement = xmlDoc.CreateElement("value");
            XmlText level = xmlDoc.CreateTextNode("1");
            levelsElement.AppendChild(levelElement);
            levelsElement.LastChild.AppendChild(level);

            // add values
            XmlElement valuesElement = xmlDoc.CreateElement("values");
            components.AppendChild(valuesElement);

            foreach (String value in this.values)
            {
                XmlElement valueElement = xmlDoc.CreateElement("value");
                XmlText txt = xmlDoc.CreateTextNode(value);

                valuesElement.AppendChild(valueElement);
                valuesElement.LastChild.AppendChild(txt);
            }

            //save xml somewhere for debugging
            try
            {
                xmlDoc.Save(@"D:\sendVariables.xml");
            }
            catch
            {
                //nothing
            }

            //turn xml into dataset
            dataSet.ReadXml(new XmlNodeReader(xmlDoc));

            // get report contents from reportservice
            switch ((Int32)Session["groepService"])
            {
                case 6:
                    displayReport(this.groep6Service.getDataset(dataSet));
                    break;
                case 7:
                    displayReport(this.groep7Service.getDataset(dataSet));
                    break;
            }
        }

        ///
        /// <summary>Displays the report</summary>
        /// <param name="reportDataSet">Dataset with the contents of the report</param>
        ///
        private void displayReport(DataSet reportDataSet)
        {
            // insert data into gridview
            grd_report.DataSource = reportDataSet;
            grd_report.DataBind();


            //try to generate a chart
            try
            {

                //-----------------------------------
                // Chart
                // ----------------------------------

                // get the first row and use that as the beginDate
                DateTime beginDate = new DateTime
                    (
                        Int32.Parse(reportDataSet.Tables[0].Rows[0][1].ToString()),
                        Int32.Parse(reportDataSet.Tables[0].Rows[0][2].ToString()),
                        1
                    );

                // make the dataArrays and set all values to -1
                float[] data1 = new float[12];
                float[] data2 = new float[12];
                for (int i = 0; i < data1.Length; i++)
                {
                    data1[i] = -1;
                    data2[i] = -1;
                }

                // highest bar value
                int highestBar = 0;

                // iterate over the rows and parse the contents
                foreach (DataRow row in reportDataSet.Tables[0].Rows)
                {
                    if (Int32.Parse(row[1].ToString()) != beginDate.Year)
                    {
                        continue;
                    }

                    if (row[0].ToString() == "CARGO TRANSPORT 5")
                    {
                        DateTime date = new DateTime
                            (
                                Int32.Parse(row[1].ToString()),
                                Int32.Parse(row[2].ToString()),
                                1
                            );

                        int value = Int32.Parse(row[3].ToString());
                        data1[date.Month - 1] = value / 10;
                        highestBar = (value > highestBar) ? value : highestBar;
                    }
                    else if (row[0].ToString() == "XRQ - TRUCK GROUND")
                    {
                        DateTime date = new DateTime
                            (
                                Int32.Parse(row[1].ToString()),
                                Int32.Parse(row[2].ToString()),
                                1
                            );

                        int value = Int32.Parse(row[3].ToString());
                        data2[date.Month - 1] = value / 10;
                        highestBar = (value > highestBar) ? value : highestBar;
                    }
                }

                // Instantiate the chart object
                BarChart chart = new BarChart(500, 600, BarChartOrientation.Vertical, BarChartStyle.Grouped);

                // values to use
                List<float[]> datasets = new List<float[]>();
                datasets.Add(data1);
                datasets.Add(data2);

                // Set chart title using default color and font
                chart.SetTitle("Monthly overview " + beginDate.Year);

                // Create the bottom X-axis that will contain the months
                ChartAxis bottomAxis = new ChartAxis(ChartAxisType.Bottom);
                bottomAxis.SetRange(1, 12);

                // Create the left X-axis that will contain the sales
                ChartAxis leftAxis = new ChartAxis(ChartAxisType.Left);
                leftAxis.SetRange(0, highestBar);

                // Add the axises
                chart.AddAxis(bottomAxis);
                chart.AddAxis(leftAxis);

                // Load the chart with the dataset (line int array)
                chart.SetData(datasets);

                // Some nice colors
                chart.SetDatasetColors(new string[] { "FF0000", "00AA00" });

                // Bar width
                chart.SetBarWidth(10);

                // Legend
                chart.SetLegend(new string[] { "Truck", "Boat" });

                // display the chart
                int scale = highestBar / 10;
                ChartImg.Src = chart.GetUrl() + "&chds=0," + scale;
            }
            catch
            {
                //doet t niet
            }
        }

        protected void btn_login_Click(object sender, EventArgs e)
        {
            String username = txt_username.Text.Trim();
            String password = txt_password.Text.Trim();

            //try loggin in
            if (securityService.checkLogin(username, password))
            {
                Response.Write("logged");
                //SecurityUser user = securityService.getUser(username);
                Session["username"] = username;
                
                Response.Redirect(Request.Url.ToString());

            }
            else
            {
                Response.Write("fail");
            }
           
        }
        
    }
}
